import UserTool from '@/utils/UserTool';
import { App, Button, message, Upload } from 'antd';
import { ButtonProps } from 'antd/es/button';
import React from 'react';

type UploadButtonProps = {
  name?: string;

  buttonProps: { btnText: string } & ButtonProps;

  /** 上传地址 */
  action: string;
  /** 附带的data */
  data?: any;
  /** 上传完成后的回调 */
  onUploadSuccess?: (response: any) => void;
  /** 上传失败后的回调 */
  onUploadError?: (error: any) => void;
  loading?: boolean;
  setLoading?: (loading: boolean) => void;
};

const UploadButton: React.FC<UploadButtonProps> = ({
  name = 'file',
  buttonProps,
  loading = false,
  setLoading = () => {},
  action,
  data = {},
  onUploadSuccess = () => {},
  onUploadError = () => {},
}) => {
  const { modal } = App.useApp();

  return (
    <Upload
      name={name}
      disabled={loading}
      showUploadList={false}
      action={action}
      headers={{
        passkey: UserTool.getUserToken(),
      }}
      data={{ ...data }}
      onChange={(info: any) => {
        const { file } = info;
        const { response, status } = file;
        if (status === 'uploading') {
          setLoading(true);
          return;
        }
        if (status === 'error') {
          message
            .error('文件上传出错，请手动刷新页面(按 Ctrl/Command + F5 )后重试')
            .then();
          setLoading(false);
          return;
        }

        if (status !== 'done') {
          return;
        }

        const { status: apiStatus, message: _message, msg } = response;
        //
        if (apiStatus !== 200) {
          // message.error(errMsg|| msg).then();
          const errMsg = _message || msg;
          // 拆分错误信息, 根据 <br/> 进行拆分成数组
          let errArr: string[] = errMsg.split('<br/>');

          modal.warning({
            content: (
              <div>
                {errArr.map((errLine) => {
                  return <p key={errLine}>{errLine}</p>;
                })}
              </div>
            ),
          });
          onUploadError(response);
          setLoading(false);
          return;
        }
        setLoading(false);
        onUploadSuccess(response);
      }}
    >
      <Button {...buttonProps} loading={loading}>
        {buttonProps.btnText}
      </Button>
    </Upload>
  );
};

export default UploadButton;
